package com.share.cloudStorage.filter;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.exceptions.ValidateException;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTException;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.JWTValidator;
import com.share.cloudStorage.constant.Constants;
import com.share.cloudStorage.model.Result;
import com.share.cloudStorage.utils.UtilFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: javaKing
 * @Date: 2024/12/09/15:25
 * @Description:
 */
@WebFilter("/*")
@Component
@Slf4j
public class SecurityFilter extends HttpFilter {

    public static ThreadLocal<Integer> userid = new ThreadLocal<>();
    public static ThreadLocal<String> adminName = new ThreadLocal<>();

    @Override
    protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String requestURI = request.getRequestURI();
        log.info("请求url{}",requestURI);

        String method = request.getMethod();
        if (method.equals("OPTIONS")){
            chain.doFilter(request,response);
            return;
        }
        //放行白名单
        String[] excludeUrls = new String[]{"/admin/createCode","/login","captcha","/admin/resetAdminPassword","searchByFileId","getShareInfo","checkShare"};
        for (String excludeUrl : excludeUrls) {
            if (requestURI.contains(excludeUrl)){
                chain.doFilter(request,response);
                return;
            }
        }
        if (requestURI.contains("/user") || requestURI.contains("/File")){
            chain.doFilter(request,response);
            return;
        }

        String token = request.getHeader(Constants.TOKEN_KEY);
        String adminToken = request.getHeader(Constants.ADMIN_TOKEN_KEY);
        try{
            if ((adminToken == null || adminToken.isEmpty() || !JWTUtil.verify(adminToken, Constants.JWT_KEY.getBytes())) && token.isEmpty()) {
                Result result = Result.fail("令牌为空，或者签名错误");
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                UtilFilter.writeResult(response,result);
                return ;
            }
            if (adminToken != null && !adminToken.isEmpty() && JWTUtil.verify(adminToken, Constants.JWT_KEY.getBytes())){
                JWTValidator.of(adminToken).validateDate(DateUtil.date());
                JWT jwt = JWTUtil.parseToken(adminToken);
                String username =  (String)jwt.getPayload(Constants.Admin_KEY);
                adminName.set(username);
                chain.doFilter(request,response);
                return;
            }
        } catch (JWTException e) {
            Result result = Result.fail("令牌无效");
            UtilFilter.writeResult(response,result);
            handleToke(request,response);
            return;
        }catch (ValidateException e){
            Result result = Result.fail("令牌过期");
            UtilFilter.writeResult(response,result);
            handleToke(request,response);
            return;
        }catch (NullPointerException e){
            handleToke(request,response);
            return;
        }
        log.info("token:{}",token);

        JWT jwt = JWTUtil.parseToken(token);

        Object payloadUserId =  jwt.getPayload(Constants.USERNAME_KEY);

        log.info("当前用户username为:{}", payloadUserId);

        userid.set(Integer.parseInt(payloadUserId.toString()));

        chain.doFilter(request,response);
    }

    public void handleToke(HttpServletRequest request,HttpServletResponse response) throws IOException {
//        String parameter = request.getParameter("link");
//        String uri = request.getRequestURI();
//        if (uri.contains("/api/v1/shares/checkShare/")){
//            parameter = uri.substring(uri.lastIndexOf("/")+1);
//        }
//
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
//        response.getWriter().write(parameter);
        response.getWriter().write("请先登录");
        response.getWriter().flush();
    }
}
